package mspbots.cw.data.core.subdata;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.common.ResultMsg;
import mspbots.cw.common.subdata.SubDataType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * com.mspbots.cw.amqp.receivers.SubdataReceiver
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/2/27
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class SubDataReceiver extends mspbots.cw.data.core.AbstractToolsUtil {

    private final SubDataRepository subDataRepository;

    @RabbitListener(queues = "connect-wise.sub-data.sync")
    public void processMessage(ResultMsg resultMsg) {

        SubData data = SubData.builder().otherId(resultMsg.getId())
                .tenantId(resultMsg.getTenantId())
                .type(SubDataType.valueOf(resultMsg.getAction()))
                .extend(resultMsg.getEntity())
                .syncTime(resultMsg.getSyncDate())
                .build();
        data.setUpdateTime(super.getUpdateTime(resultMsg.getEntity()));
        data.setCreateTime(super.getCreateTime(resultMsg.getEntity()));

        this.subDataRepository.findByOtherIdAndTenantIdAndType(resultMsg.getId(), resultMsg.getTenantId(), data.getType())
                .switchIfEmpty(this.subDataRepository.save(data))
                .filter(old -> old.getUpdateTime().isBefore(data.getUpdateTime()))
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .flatMap(this.subDataRepository::save).block(Duration.ofSeconds(10));

    }
}
